﻿using AQBHLib;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net.Http.Headers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using 充电桩上位机.Model.ModbusRegisters.User;
namespace 充电桩上位机.ViewModel.SerialPortConnection;

public class SerialPortConnectionViewModel : ObservableObject
{
    [Category("选中串口名称")]
    private TextBlock? _selPortName;
    public TextBlock? SelPortName
    {
        get => _selPortName;
        set {
            BaudRateIndex = 0;
            SetProperty(ref _selPortName, value); 
        }
    }
    private int? _baudRateIndex;
    public int? BaudRateIndex
    {
        get => _baudRateIndex;
        set => SetProperty(ref _baudRateIndex, value);
    }
    [Category("串口群名称")]
    private ObservableCollection<TextBlock> _hubNamelist = new();
    public ObservableCollection<TextBlock> HubNamelist
    {
        get => _hubNamelist;
        set => SetProperty(ref _hubNamelist, value);
    }
    [Category("选中串口波特率")]
    private TextBlock? _baudRate;
    public TextBlock? BaudRate
    {
        get => _baudRate;
        set => SetProperty(ref _baudRate, value);
    }
    [Category("串口群名称")]
    private ObservableCollection<TextBlock> _baudRatelist = new();
    public ObservableCollection<TextBlock> BaudRatelist
    {
        get => _baudRatelist;
        set => SetProperty(ref _baudRatelist, value);
    }

    [Category("自动按下颜色")]
    private Brush _toggleBackGround = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2563EB"));
    public Brush ToggleBackGround
    {
        get => _toggleBackGround;
        set => SetProperty(ref _toggleBackGround, value);
    }

    [Category("刷新")]
    public ICommand ReFreshSerialCommand =>
    new RelayCommand(async () => await ReFreshSerialCommandFunc());
    [Category("连接Or断开")]
    public static bool _joinCommand = false;
    public bool JoinCommand
    {
        get => _joinCommand;
        set {
            var _ = JoinCommandFunc(value).Result;
            if (!string.IsNullOrEmpty(_))
            {
                var uiMessageBox = new Wpf.Ui.Controls.MessageBox
                {
                    Title = "Error",
                    Content =
                       _,
                };
                var result = uiMessageBox.ShowDialogAsync();
                return;
            }

            if (value)
            {
                //获取广播得到的slave addr                 
                iAQBHController.AQBHSendData(0, (ushort)mB_UserRegisiters.Modbus地址, [0x01]);
                JoinText = "break";
                ToggleBackGround = Brushes.Black;
            }
            else
            {
                JoinText = "Join";
                ToggleBackGround = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2563EB"));
            }
            SetProperty(ref _joinCommand, value);
        }
    }
    private string _joinText = "Join";
    public string JoinText
    {
        get => _joinText;
        set => SetProperty(ref _joinText, value);
    }
    #region 逻辑层
    private async Task ReFreshSerialCommandFunc()
    {
        //normal 变更
        await Application.Current.Dispatcher.InvokeAsync(delegate
        {
            HubNamelist.Clear();
            BaudRatelist.Clear();

            var pnames = System.IO.Ports.SerialPort.GetPortNames().ToList();
            foreach (var pname in pnames) {
                HubNamelist.Add(new TextBlock { Text = pname, FontSize = 14, HorizontalAlignment = HorizontalAlignment.Left, Width = 280 });
            }

            string _appStartupPath = Path.GetDirectoryName(Environment.ProcessPath)!;
            string _config = new(Path.Combine
                        (_appStartupPath!, @"Configration.json"));

            string json = File.ReadAllText(_config);
            dynamic data = JsonConvert.DeserializeObject(json)!;
            var blist = new ObservableCollection<string>(((string)data.BaudRatelist).Split(',').ToList());
            foreach (var b in blist)
            {
                BaudRatelist.Add(new TextBlock { Text = b, FontSize = 16, HorizontalAlignment = HorizontalAlignment.Left, Width = 280 });
            }

            SelPortName = null;
            BaudRate = null;

            JoinCommand = false;
        });
        await Task.Delay(2);
    }
    private Task<string> JoinCommandFunc(bool value)
    {
        //连接并获取slave id
        string result = string.Empty;
        if (value)
        {
            result = iAQBHController.AQBHPortLink(SelPortName!.Text, int.Parse(BaudRate!.Text)).Result;
            //读一下配置是否为要使用的内容，
        }
        else
            iAQBHController.AQBHPortClose();
        return Task.FromResult(result);
    }
    #endregion
    public static IAQBHController iAQBHController = new AQBHController();
    [Category("标题")]
    private string? _serial_port_connection;
    public string? Serial_port_connection
    {
        get => _serial_port_connection;
        set => SetProperty(ref _serial_port_connection, value);
    }
    [Category("端口号")]
    private string? _cOMText;
    public string? COMText
    {
        get => _cOMText;
        set => SetProperty(ref _cOMText, value);
    }
    [Category("波特率")]
    private string? _rS485_Baud_Rate;
    public string? RS485_Baud_Rate
    {
        get => _rS485_Baud_Rate;
        set => SetProperty(ref _rS485_Baud_Rate, value);
    }
    
    public SerialPortConnectionViewModel()
    {
        string _appStartupPath = Path.GetDirectoryName(Environment.ProcessPath)!;
        string _config = new(Path.Combine
                    (_appStartupPath!, @"Configration.json"));

        string json = File.ReadAllText(_config);
        dynamic data = JsonConvert.DeserializeObject(json)!;

        var pnames = System.IO.Ports.SerialPort.GetPortNames().ToList();
        foreach (var pname in pnames)
        {
            HubNamelist.Add(new TextBlock { Text = pname, FontSize = 14, HorizontalAlignment = HorizontalAlignment.Left, Width = 280 });
        }

        SelPortName = HubNamelist.Where(x => x.Text == (string)data.PortName).FirstOrDefault();

        var blist = new ObservableCollection<string>(((string)data.BaudRatelist).Split(',').ToList());
        foreach (var b in blist)
        {
            BaudRatelist.Add(new TextBlock { Text = b, FontSize = 16, HorizontalAlignment = HorizontalAlignment.Left, Width = 280 });
        }
        BaudRate = BaudRatelist.Where(x => x.Text == (string)data.BaudRate).FirstOrDefault();
        Serial_port_connection = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "Serial port connection");
        COMText = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "COM");
        RS485_Baud_Rate = MainWindowViewModel.SetLanguage(MainWindowViewModel.globellanguage, "RS485 Baud Rate");
    }
}
